<template>
    <div>
        <AMapVue ref="amapRef" map-style="615b4e4ff0bac29da3d491b357ea6f52"></AMapVue>
    </div>
</template>

<script setup lang="ts">
import AMapVue from 'src/components/AMap/AMap.vue';
import { ComputedRef, inject, onMounted, ref } from 'vue';
import { useVideoLoader, VideoSource } from '../监控视频/api';
import icon from './assets/摄像头.svg'
import * as api from './api'
const villageId = inject<ComputedRef<string>>('villageId')!
const villagePromise = api.villageDetail(villageId.value)
const emit = defineEmits<{
    (event: 'select', value: VideoSource): void
}>()
const amapRef = ref<InstanceType<typeof AMapVue>>()

const loader = useVideoLoader(villageId.value)

onMounted(async () => {
    refresh()
    const amap = amapRef.value!
    const map = await amap.ready
    map.setPitch(45)
    map.setZoom(19)
})



async function refresh() {
    const videos = await loader.load()
    const amap = amapRef.value!
    const map = await amap.ready
    map.clearMap()
    const size = new AMap.Size(40, 40)
    const videoIcon = new AMap.Icon({
        size: size,
        image: icon,
        imageOffset: new AMap.Pixel(0, 0),
        imageSize: size
    });
    const locatedVideos = videos.filter(video => video.lng && video.lat)
    locatedVideos.forEach(video => {
        const marker = new AMap.Marker({
            position: [video.lng, video.lat],
            offset: new AMap.Pixel(0, 0),
            icon: videoIcon, // 添加 Icon 实例
            anchor: 'bottom-center'
        });
        marker.on('click', () => {
            console.log(video)
            emit('select', video)
        })
        map.add(marker)
    })
    if (locatedVideos.length) {
        map.setFitView(undefined, false, [20, 270, 370, 370], 19)
    } else {
        const village = await villagePromise
        if (village.lngLat) {
            const lngLat = village.lngLat.split(',').map(parseFloat)
            map.setCenter([lngLat[0], lngLat[1]])
        }
    }
}

</script>

<style scoped>
.amap {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    mask-image: url(./assets/Union-01.png);
    mask-size: 100% 100%;
    background-color: black;
}
</style>